import { defineStore } from 'pinia';

const TOKEN_KEY = 'authToken';
const TOKEN_TIMESTAMP_KEY = 'authTokenTimestamp';
const TOKEN_EXPIRE_TIME = 24 * 60 * 60 * 1000; // 24 小时

export const useUserStore = defineStore('auth', {
  state: () => ({
    token: null as string | null,
  }),
  getters: { 
    // 添加计算登录状态
    isLoggedIn: (state) => !!state.token,
    },
  actions: {
    loadToken() {
      const token = localStorage.getItem(TOKEN_KEY);
      const timestamp = localStorage.getItem(TOKEN_TIMESTAMP_KEY);

      if (token && timestamp) {
        const now = Date.now();
        if (now - parseInt(timestamp) < TOKEN_EXPIRE_TIME) {
          this.token = token;
        } else {
          this.clearToken();
        }
      }
    },
    setToken(newToken: string) {
      this.token = newToken;
      if (newToken) {
        localStorage.setItem(TOKEN_KEY, newToken);
        localStorage.setItem(TOKEN_TIMESTAMP_KEY, Date.now().toString());
      } else {
        this.clearToken();
      }
    },
    clearToken() {
      this.token = null;
      localStorage.removeItem(TOKEN_KEY);
      localStorage.removeItem(TOKEN_TIMESTAMP_KEY);
    },
  },
});
